import json
import sys
import boto3
import os
import redis

redis_db = redis.Redis(host='106.75.35.45', port=6379, db=6, password='953058009',
                       decode_responses=True, charset='UTF-8', encoding='UTF-8')


# 获取访问秘钥
def get_ak():
    return 'hVJOTTy1XzOAiFgCIGD4'


# 获取安全秘钥信息
def get_sk():
    return 's8Lku8P2xAWRnaxwHmeHsRzsjIT0xvMmWDOJuFKM'


# 获取节点地址
def get_endpoint():
    return 'https://oss-cn-quanzhou.kz.cc'


# 客户端请求封装
def get_client(ak, sk, endpoint):
    return boto3.resource('s3', endpoint_url=endpoint, aws_access_key_id=sk, aws_secret_access_key=ak)


# 获取我的s3 client
def my_client():
    return get_client(get_ak(), get_sk(), get_endpoint())


# 上传文件
def upload_file(bucket, file_path, key):
    s3 = boto3.resource('s3', endpoint_url=get_endpoint(), aws_access_key_id=get_ak(), aws_secret_access_key=get_sk())
    return s3.meta.client.upload_file(file_path, bucket, key, {"ACL": "public-read"}, upload_progress)


# 下载文件
def download(bucket, key, download_name):
    s3 = boto3.resource('s3', endpoint_url=get_endpoint(), aws_access_key_id=get_ak(), aws_secret_access_key=get_sk())
    return s3.Object(bucket, key).download_file(download_name)


# 获取上传的信息
def upload_progress(data):
    print(data)


# 获取文件夹下所有子级的文件名称
def get_file(dirname=r'G:/apply/'):
    if not os.path.exists(dirname):
        print('该文件夹不存在')
        sys.exit()

    file_list = []
    # 递归获取子级
    for root, dirs, files in os.walk(dirname):
        for file in files:
            path = os.path.join(root, file)
            #         if path[-3:] == 'apk':
            file_list.append(path)
    return file_list


# 获取下载的文件数据
def get_redis_data(name=''):
    list = redis_db.get(name)
    return json.loads(list)


# redis拿数据
# file_list = get_redis_data('ucloud_oss_4s4a')
file_list = get_file()


# 开始去上传
num = 0
for path in file_list:
    num += 1
    filename = path.replace("G:/apply/", 'game/')
    if os.access(path, os.F_OK):
        try:
            upload_file('website-uniapp', path, filename)
            with open('file.txt', 'a') as w:
                w.write('第' + str(num) + '个文件->'+filename+'<-已上传完成-------->' + filename + '\n')
                w.close()
        except Exception:
            with open('file_error.txt', 'a') as w:
                w.write('第' + str(num) + '个文件->'+filename+'<-上传失败-------->' + filename + '\n')
                w.close()
        print('第' + str(num) + '个文件->'+filename+'<-已上传完成')
